import axios from 'axios'
import router from '../router'
import cookie from 'vue-cookie'

window.axios = axios
window.cookie = cookie

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    const token = cookie.get('token')
    if (!token) {
      next({
        path: '/login',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  if (to.path === '/login') {
    const token = cookie.get('token')
    if (token) {
      next({
        path: '/home',
        query: {reffer: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  next()
})

// http request 拦截器
axios.interceptors.request.use(
  config => {
    const token = cookie.get('token')
    if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.token = `${token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.code === 401) {
      cookie.delete('token')
      router.replace({
        path: '/index',
        query: {redirect: router.currentRoute.fullPath}
      })
    } else if (response.code === 404) {
      // this.$message.error('接口不存在')
      return
    }
    let data = response.data
    if (data.code === 404) {
      // this.$message.error('接口不存在')
      return
    } else if (data.code === 403) {
      router.replace({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath}
      })
      // this.$message.error('无权限访问')
      return
    } else if (data.code > 0) {
      // this.$message.error(data.message)
      return
    }
    return response
  },
  error => {
    return Promise.reject(error)   // 返回接口返回的错误信息
  }
)
